<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<div style="margin: 0 auto 0 auto; width: 50%">
	<form:form id="frmUser" modelAttribute="user" method="post">
		<legend>Crear usuario</legend>
		<label>Nombre de usuario</label>
		<form:input path="userName" />
		<label>Contrase&ntilde;a</label>
		<form:password path="password" />
		<label>Repetir contrase&ntilde;a</label>
		<input type="password" id="repeat_password" name="repeat_password" />
		<label>Seleccione el grupo o grupos a los que pertenece el
			usuario</label>
		<form:select path="groups">
			<form:option value="" selected="selected">---</form:option>
			<form:options items="${groups}" itemValue="id" itemLabel="groupName" />
		</form:select>
		<label><button type="submit" class="btn">Submit</button></label>
	</form:form>
</div>

<div id="dlgUserInfo" class="modal hide fade">
	<div class="modal-header">		
		<h3>Informaci&oacute;n</h3>
	</div>
	<div class="modal-body">
		<p>El usuario ha sido creado</p>
	</div>
	<div class="modal-footer">
		<a href="#" id="btnUserList" class="btn btn-primary">Aceptar</a>
	</div>
</div>
<script type="text/javascript">
	require([ 'jquery', 'jqueryvalidate', 'jqueryform', 'jsonserialize',
			'bootstrap' ], function($) {
		$(document).ready(function() {			
			$("#dlgUserInfo").modal({
				keyboard : false,
				show:false
			}).find("#btnUserList").click(function(){
				document.getElementById("frmUser").reset();
				$("#dlgUserInfo").modal("hide");
				$("#userName").focus();
			});
			
			$.validator.addMethod('user_taken', function(value, element) {
				var isSuccess = false;
				$.ajax({
					url : "validate_repeated_user",
					data : {
						userName : value
					},
					async : false,
					dataType : "json",
					success : function(result) {
						isSuccess = !result.exists;
					}
				});
				return isSuccess;
			}, 'El nombre de usuario ya ha sido tomado');

			$("form").validate({
				rules : {
					userName : {
						'required' : true,
						'user_taken' : true
					},
					password : 'required',
					repeat_password : {
						equalTo : '#password'
					},
					groups : {
						required : true
					}
				},
				submitHandler : function(form) {
					var user = $(form).serializeObject();
					$.postJSON("", user, function(result) {
						$("#dlgUserInfo").modal('show');
					});
				}
			});

		});
	});
</script>
